#include "07_TcpServer.hpp"
#include "13_EchoServer.hpp"
#include <stdio.h>

#define info_msg(msg) do { \
    printf("%s | %d | %s | %s \n", __FILE__, __LINE__, __FUNCTION__, msg); \
} while(0)

namespace xy{
TcpServer::TcpServer(short unsigned port, const std::string& ip)
    :_acceptor(port, ip)
    ,_event_loop(_acceptor)
    ,_is_running(false){}
    //,_thread(false){}         // 笔误，给编译器整不会了, _thread不需要初始化，而是在start中创建

TcpServer::~TcpServer()
{
    if(_is_running)
    {
        info_msg("stop start");
        stop();
        info_msg("stop successful");
    }
}

void TcpServer::start()
{
    if(_is_running) return;

    _acceptor.ready();
    info_msg("Server running on port 8080...\n");
    
    // 这些设置被新增的13_EchoServer.cpp的设置所覆盖
    //_event_loop.set_connection_callback(xy::on_connection);
    //_event_loop.set_message_callback(xy::on_message);
    //_event_loop.set_close_callback(xy::on_close);

    _is_running = true;

    // 时间循环在一个单独的线程中运行，这样主线程就可以调用stop()方法
    // 在start()方法中正确创建线程
    _thread = std::thread(
        [this](){
        _event_loop.loop();
        }
    );
}

void TcpServer::stop()
{
    if(!_is_running) return;

    info_msg("start unloop");
    _event_loop.unloop();
    info_msg("start joinable");
    if(_thread.joinable())
    {
        _thread.join();
    }
    _is_running = false;
    info_msg("Server stopped...\n");
}
}
